<?php

namespace app\common\service\driver;

use think\Exception;

/**
 * 七牛云存储驱动
 */
class QiniuDriver
{
    protected $config;
    protected $auth;
    protected $uploadManager;

    public function __construct($config)
    {
        $this->config = $config;
        $this->initQiniu();
    }

    /**
     * 初始化七牛云
     */
    protected function initQiniu()
    {
        $configData = $this->config->config;
        
        if (empty($configData['access_key']) || empty($configData['secret_key'])) {
            throw new Exception('七牛云配置不完整：缺少AccessKey或SecretKey');
        }
        
        if (empty($configData['bucket']) || empty($configData['domain'])) {
            throw new Exception('七牛云配置不完整：缺少Bucket或Domain');
        }
        
        // 这里需要引入七牛云SDK
        // 实际使用时需要安装：composer require qiniu/php-sdk
        try {
            $this->auth = new \Qiniu\Auth($configData['access_key'], $configData['secret_key']);
            $this->uploadManager = new \Qiniu\Storage\UploadManager();
        } catch (\Exception $e) {
            throw new Exception('七牛云连接失败：' . $e->getMessage());
        }
    }

    /**
     * 上传文件
     */
    public function upload($file, $fileInfo)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        $key = $fileInfo['file_path'];
        
        try {
            $token = $this->auth->uploadToken($bucket);
            list($ret, $err) = $this->uploadManager->putFile($token, $key, $file->getRealPath());
            
            if ($err !== null) {
                throw new Exception('七牛云上传失败：' . $err->message());
            }
            
            // 生成访问URL
            $domain = $configData['domain'];
            $fileUrl = rtrim($domain, '/') . '/' . $key;
            
            return [
                'file_path' => $fileInfo['file_path'],
                'file_url' => $fileUrl
            ];
        } catch (\Exception $e) {
            throw new Exception('七牛云上传失败：' . $e->getMessage());
        }
    }

    /**
     * 删除文件
     */
    public function delete($filePath)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        
        try {
            $bucketManager = new \Qiniu\Storage\BucketManager($this->auth);
            list($ret, $err) = $bucketManager->delete($bucket, $filePath);
            
            if ($err !== null) {
                throw new Exception('七牛云删除失败：' . $err->message());
            }
            
            return true;
        } catch (\Exception $e) {
            throw new Exception('七牛云删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取文件URL
     */
    public function getUrl($filePath)
    {
        $configData = $this->config->config;
        $domain = $configData['domain'];
        
        return rtrim($domain, '/') . '/' . $filePath;
    }

    /**
     * 检查文件是否存在
     */
    public function exists($filePath)
    {
        $configData = $this->config->config;
        $bucket = $configData['bucket'];
        
        try {
            $bucketManager = new \Qiniu\Storage\BucketManager($this->auth);
            list($ret, $err) = $bucketManager->stat($bucket, $filePath);
            
            return $err === null;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 测试连接
     */
    public function test()
    {
        try {
            $bucketManager = new \Qiniu\Storage\BucketManager($this->auth);
            list($ret, $err) = $bucketManager->listFiles($this->config->config['bucket'], null, null, 1);
            
            if ($err !== null) {
                throw new Exception($err->message());
            }
            
            return true;
        } catch (\Exception $e) {
            throw new Exception('七牛云连接测试失败：' . $e->getMessage());
        }
    }
}
